package com.example.chatapp.service;

import com.example.chatapp.manager.RedisCacheManager;
import com.example.chatapp.manager.RedisMessageQueueManager;
import com.example.chatapp.model.MessageEntity;
import com.example.chatapp.repository.MessageRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 聊天服务
 * 职责：纯业务逻辑，不涉及基础设施细节
 */
@Service
public class ChatService {

    private final MessageRepository messageRepository;
    private final RedisCacheManager cacheManager;
    private final RedisMessageQueueManager messageQueueManager;

    public ChatService(MessageRepository messageRepository,
                       RedisCacheManager cacheManager,
                       RedisMessageQueueManager messageQueueManager) {
        this.messageRepository = messageRepository;
        this.cacheManager = cacheManager;
        this.messageQueueManager = messageQueueManager;
    }

    /**
     * 持久化消息（带事务）
     */
    @Transactional
    public void saveMessage(String roomId, long seq, String sender, String toUser, 
                           String jsonPayload, boolean isSystem) {
        MessageEntity entity = new MessageEntity();
        entity.setRoomId(roomId);
        entity.setSeq(seq);
        entity.setSender(sender);
        entity.setToUser(toUser);
        entity.setContent(jsonPayload);
        entity.setIsSystem(isSystem);
        
        messageRepository.save(entity);
        System.out.println("[ChatService] Message saved: seq=" + seq + ", room=" + roomId);
    }

    /**
     * 缓存最近消息
     */
    public void cacheRecentMessage(String roomId, String messageJson) {
        cacheManager.pushRecentMessage(roomId, messageJson);
    }

    /**
     * 获取最近消息
     */
    public List<Object> getRecentMessages(String roomId, int limit) {
        return cacheManager.getRecentMessages(roomId, limit);
    }

    /**
     * 获取历史消息（从数据库）
     */
    public List<MessageEntity> getHistoryMessagesSince(String roomId, long sinceSeq) {
        return messageRepository.findByRoomIdAndSeqGreaterThanOrderBySeqAsc(roomId, sinceSeq);
    }

    /**
     * 确保订阅房间频道
     */
    public void ensureRoomSubscribed(String roomId) {
        messageQueueManager.ensureSubscribed(roomId);
    }

    /**
     * 检查房间是否已订阅
     */
    public boolean isRoomSubscribed(String roomId) {
        return messageQueueManager.isSubscribed(roomId);
    }
}
